<?php
namespace Fn;
class System{
	
	static function tmpFile($p){
		return TEMP_PATH.$p;
	}
	
	static function getOsName(){
		return strstr(strtolower(php_uname('s')),'windows')? 'windows':'linux';
	}

	static function testRenderPdfByUrl($url,$outputFile,$param=array()){
    	try {
    		set_time_limit(15);
    	} catch (Exception $e) {
    		
    	}
    	$url = '"'.addslashes($url).'"';
        $param = empty($param)? '':implode(' ',$param);
        $scriptFile = __DIR__.'/scripts/html_render_to_pdf.js';
        $tmpRes = exec('phantomjs '.$scriptFile.' '.$url.' '.$outputFile.$param, $output);
        $output = implode("\n",$output);
        $outputArr = explode('[##--CONTENT--##]',$output);
        if(!empty($outputArr) && count($outputArr)>1){
            list($output) = explode('[/##--CONTENT--##]',$outputArr[1].'[/##--CONTENT--##]');
            $r = str_replace('json://','',$output);
            if($r != $output){
                return json_decode($r,true);
            }else{
                return $r;
            }
        }
        return false;
    }
    static function renderPdfByUrl($url,$outputFile,$param=array()){
    	try {
    		set_time_limit(15);
    	} catch (Exception $e) {
    		
    	}
    	$url = '"'.addslashes($url).'"';
        $param = empty($param)? '':implode(' ',$param);
        $scriptFile = __DIR__.'/scripts/html_render_to_pdf.js';
        $tmpRes = exec('/usr/local/bin/phantomjs '.$scriptFile.' '.$url.' '.$outputFile.$param, $output);
	    // $tmpRes = exec('phantomjs '.$scriptFile.' '.$url.' '.$outputFile.$param, $output);
	   	// App::log('chenyong1115','phantomjs '.$scriptFile.' '.$url.' '.$outputFile.$param,"测试svg 0011");
	   	// print_r('phantomjs '.$scriptFile.' '.$url.' '.$outputFile.$param);
        $output = implode("\n",$output);
        $outputArr = explode('[##--CONTENT--##]',$output);
        if(!empty($outputArr) && count($outputArr)>1){
            list($output) = explode('[/##--CONTENT--##]',$outputArr[1].'[/##--CONTENT--##]');
            $r = str_replace('json://','',$output);
            if($r != $output){
                return json_decode($r,true);
            }else{
                return $r;
            }
        }
        return false;
    }

	static function renderPdfUrlByApi($url,$param=array()){
		$proxyParam = http_build_query(array('url'=>urlencode($url),'param'=>json_encode($param),'encode'=>'json' ));
		$proxyUrl = 'http://118.31.169.240/getCaseNumberPdfApi.php?'.$proxyParam;
		$response = Http::curl($proxyUrl);
		return $response;
	}

    static function renderPdfByApi($url,$outputFile,$param=array()){
    	// print_r($url);die();
    	// $url = 'http://hittime.net:8080/erp/index.php?s=Erp-Orders-xpublic&cmd=GetSvgLabel&ordersId=1123056221';
    	$proxyParam = http_build_query(array('url'=>urlencode($url),'param'=>json_encode($param),'encode'=>'json' ));
    	$proxyUrl = 'http://118.31.169.240/getSvgPdfApi.php?'.$proxyParam;
    	// $response = file_get_contents($proxyUrl);print_r($response) ;die();
    	//$tmpUrl = 'http://localhost/erp/2index.php?s=Erp-Orders-xpublic&cmd=GetSvgLabel&ordersId=1122719217';
    	$response = Http::curl($proxyUrl);
    	if(strpos($response,'[EROOR][EROOR]') === false){
    		$size = file_put_contents($outputFile, $response);
    		if(($size/1024)>16){
    			return array('success'=>true,'msg'=>'ok');
    		}
    	}
    	return false;
    }

	static function curl($url,$background = true){
		$win = self::getOsName()==='windows' ;
		if($background){
			if($win){
				$str = "php -r 'file_get_content(\"$url\");'";
				file_put_contents(self::tmpFile('tmp.bat'),$str);
				return self::tmpFile('tmp.bat');
			}
			return exec("(curl '$url'>>/dev/null &)");
		}else{ 
			if($win) return file_get_contents($url);
			return exec('curl "'.$url.'"');
		}
	}
	
	static function cmd($c,$background=true ,$output='')
	{
		file_put_contents(self::tmpFile('cmd-list'),  time()."\t".$c."\n",  FILE_APPEND);

		$output = empty($output)? self::tmpFile('cmd-log-'.date('y-m-d').'.log'):$output;
		$r = array();
		if(!file_exists($output)){
			file_put_contents($output,' ');
			chmod($output,0777);
		}
		if($background){ exec("($c>>$output &)", $r); }
		else{  exec($c, $r); }
		return $r;
	}

    static function rm($file,$recursion = false)
    {
        echo $file;
        if(is_dir($file)) {
            if($recursion) {
                $filesList = glob(rtrim($file, '/') . '/*');
                if (!empty($filesList)) {
                    foreach ($filesList as $v) {
                        self::rm($v,$recursion);
                    }
                }
            }
            return rmdir($file);
        }else {
            return unlink($file);
        }
    }
    /*
     * exp:C:/aaa/aaa.txt to C:/aaa/aaa.txt.zip
     * @param from = aaa.txt,
     * @param to C:/aaa/aaa.txt
     * @param changeDir  C:/aaa;
     */
    static function zip($from,$to,$changeDir=false,$background=false)
    {
        $logFile = str_replace(array('/','\\'),'', (__CLASS__.'-'.__FUNCTION__) );

        $debug = i('get._debug_','no','trim')==='yes';
        $changeDir =  realpath($changeDir);
        $nowPaht = getcwd();
        $chDirRes = true;

        //if($debug) echo ($changeDir.'将修改运行目录'."\n<br>");
        if($changeDir) $chDirRes = chdir($changeDir);
        //if($debug) echo getcwd()."更改目录后<br>\n";

        if (self::getOsName() === 'windows') {
            $cmd = "rar a -r -va $to $from";
        } else{
            $cmd = "zip -r $to $from";
        }

        //if($debug) echo $cmd."\n<br>";
        if($chDirRes) $r = exec($cmd);
        else  $r = false;

        if($changeDir) if(!chdir($nowPaht)) chdir($nowPaht);
        return $r;
    }
	static function checkPs($keyword){
		$grpCmd = 'grep '.$keyword; 
		$cmd = 'ps -ef|'.$grpCmd;
		$r = self::cmd( $cmd, false );
		return $r;
		//$r = str_replace($grpCmd,'_GREPGREPGREP_',$r);
		//return strpos($r,$keyword);
	}
	
	static function killPsByKeyword($keyword,$background = true){
		//$ps = "ps aux|grep $keyword|awk '{print $2}'|xargs kill -9";
		//return self::cmd( $cmd, $background );
	}
	
	static function childProcess($file, $arg = array(),$background = true){

		if(!empty($arg)){
			$arg = ' '.implode(' ', $arg);
			if(stristr(' '.$arg.' ',' Erp-Public-childProcessDaemon ')) return false;
		}else {
			$arg = '';
		}
		$cmd = "php $file$arg";
		if(self::getOsName()==='windows'){
			if($background) file_put_contents(self::tmpFile(microtime(true).'.wincmd.log'), $cmd);
			else self::cmd("php $file$arg", false);
			return ;
		}else{
			return self::cmd("php $file$arg", $background);
		}
	}

	static function childProcessForWindowsDaemon()
	{
		exec('chcp 936');
		//exec('chcp 65001');
		//exec('color 2B');
		$pathForApp = self::stdin("请输入项目入口文件所在的目录", function($res){return empty($pathForApp) || is_dir($res);});
		if(!empty($pathForApp)) chdir($pathForApp);
		
		$i = 0;
		self::stdout("\n------------\n正在等待异步命令的发送\n");
		while (1) {			
			self::_childProcessForWindowsListeners();
			$i++;
			sleep(3);
		}
	}
	
	/*
	*
	*/

	private static function _childProcessForWindowsListeners(){
		$files = glob(self::tmpFile('*.wincmd.log'));
		if(!empty($files)){
			self::stdout("已经收到 ".count($files)."条命令\n");
			foreach ($files as $key => $f) {
				$cmd = file_get_contents($f);
				@unlink($f);
				$res = '';
				self::stdout("\n--------------\n命令: ".$cmd."\n--------------\n");
				if($cmd){
					exec($cmd,$res);
					self::stdout("结果:\n");
					self::stdout($res);
				}
			}
		}
	}

	static function stdin($msg,$callback=false){
		self::stdout($msg.':');
		$stdin=fopen('php://stdin','r');
		$content=trim(fgets($stdin,100));
		fclose($stdin);
		if($callback && is_callable($callback) ){
		    if(!call_user_func($content)) {
                self::stdout("输入不正确!!!\n");
                $content = self::stdin($msg, $callback);
            }
		}
		return $content;
	}

	static function stdout($str){
		$str = is_array($str)? implode("\n", $str): $str;
		echo iconv('utf-8','gbk',$str); 
	}

}